import { createApp } from "vue";
import App from "./App.vue";
import Vant from "vant";
import "vant/lib/index.css";

import router from "./routers/index";
import ApiList from "./api/index.js";
import VueCookies from "vue-cookies";

import pathArr from "./routers/pathArr";

const app = createApp(App)
  .use(Vant)
  .use(router)
  .use(ApiList)
  .use(VueCookies)
  .mount("#app");

router.beforeEach(async (to, from, next) => {
  let cookie = app.$cookies.get("ShopUser");
  // console.log(cookie);
  if (pathArr.indexOf(to.path) !== -1) {
    next();
  } else {
    if (cookie) {
      // TODO 发起请求查看cookie是否是合法的，查数据库
      let userid = cookie.id ? cookie.id : 0;
      // console.log(cookie);
      let res = await app.$api.check({ userid });

      if (res.code === 1) {
        // TODO 覆盖cookies
        app.$cookies.set("ShopUser", res.data);
        next();
      } else if(res.code) {
        app.$notify({
          type: "danger",
          message: res.msg,
          duration: 1500,
          // onClose: () => {
          //   app.$cookies.remove("LoginUser");
          //   return;
          // },
        });
        app.$cookies.remove("ShopUser");
        return false;
      }
    } else {
      // TODO 此方法内无法使用回调函数
      app.$notify({
        type: "warning",
        message: "请先登录",
        // onClose: () => {

        // },
      });
      next("/user/base/login");
      return false;
    }
  }
});

// router.beforeEach(async (to, from, next) => {
//   if (to.meta.auth) {
//     let ShopUser = app.$cookies.get("ShopUser");

//     if (!ShopUser) {
//       next("/user/base/login");
//       return;
//     }

//     //获取id
//     let userid = ShopUser.id ? ShopUser.id : 0;

//     //接口请求
//     let result = await api.check(userid);

//     console.log(result);
//     if (result.code === 0) {
//       //验证失败
//       app.$cookies.remove("ShopUser");

//       //跳转了
//       next("/user/base/login");
//       return;
//     } else {
//       //验证成功
//       //覆盖cookie
//       app.$cookies.set("ShopUser", result.data);
//       //让他去到该去的路由
//       next();
//     }
//   } else {
//     //不需要登录,直接跳转路由
//     next();
//   }
// });
